<template>
  <div class="unified-login-container">
    <div class="login-card">
      <!-- 顶部标题 -->
      <div class="login-header">
        <h2 class="main-title">智能小说平台</h2>
        <p class="subtitle">欢迎登录</p>
      </div>

      <!-- 钉钉登录按钮 -->
      <div class="dingtalk-login-section">
        <a :href="ddUrl" class="dingtalk-btn" @click.prevent="handleDingTalkLogin">
          <span class="btn-icon">📱</span>
          钉钉登录
        </a>
        <div class="divider">
          <span>或</span>
        </div>
      </div>

      <!-- 统一授权登录按钮 -->
      <!-- 授权登录已下线 -->

      <!-- 登录内容区 -->
      <div class="login-content">
        <!-- 账号密码登录 -->
        <div class="account-login content-fade">
          <form @submit.prevent="handleAccountLogin">
            <div class="form-group">
              <label>手机号</label>
              <input 
                v-model="loginForm.phone" 
                type="text" 
                placeholder="请输入手机号"
                class="form-input"
              />
            </div>

            <div class="form-group">
              <label>密码</label>
              <input 
                v-model="loginForm.password" 
                type="password" 
                placeholder="请输入密码"
                class="form-input"
              />
            </div>

            <div class="form-options">
              <label class="checkbox-label">
                <input type="checkbox" v-model="loginForm.remember" />
                <span>记住我</span>
              </label>
              <a href="#" class="forgot-link">忘记密码？</a>
            </div>

            <button type="submit" class="login-button" :disabled="!canSubmit">
              {{ loginLoading ? '登录中...' : '登录' }}
            </button>

            <div class="register-tip">
              还没有账号？<a href="#" @click.prevent="goToRegister">立即注册</a>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'UnifiedLogin',
  data() {
    return {
      loginLoading: false,
      ddUrl: '',
      loginForm: {
        phone: '',
        password: '',
        remember: false
      }
    }
  },
  mounted() {
    // 获取钉钉登录URL
    this.getDingTalkUrl()
    
    // 处理钉钉回调
    this.handleDingTalkCallback()
  },
  computed: {
    canSubmit() {
      return this.loginForm.phone && this.loginForm.password && !this.loginLoading
    }
  },
  methods: {
    /**
     * 处理钉钉登录点击
     */
    async handleDingTalkLogin() {
      if (!this.ddUrl) {
        alert('正在获取登录链接，请稍候...')
        await this.getDingTalkUrl()
      }
      if (this.ddUrl) {
        window.location.href = this.ddUrl
      } else {
        alert('获取钉钉登录链接失败，请检查网络连接')
      }
    },
    
    /**
     * 获取钉钉登录URL
     */
    async getDingTalkUrl() {
      try {
        const { userAPI } = await import('@/api/user')
        const res = await userAPI.getDingTalkUrl()
        console.log('钉钉登录URL响应:', res)
        
        // 后端返回格式可能是 {url: "..."} 或 {data: {url: "..."}}
        if (res && res.url) {
          this.ddUrl = res.url
        } else if (res && res.data && res.data.url) {
          this.ddUrl = res.data.url
        } else {
          console.error('无法解析钉钉URL:', res)
        }
      } catch (error) {
        console.error('获取钉钉登录URL失败:', error)
      }
    },

    /**
     * 处理钉钉登录回调
     */
    async handleDingTalkCallback() {
      // 检查URL中是否有code参数
      const urlParams = new URLSearchParams(window.location.search)
      const code = urlParams.get('code')
      
      if (!code) return

      try {
        // 调用后端钉钉回调接口
        const res = await fetch(`http://127.0.0.1:8000/user/dingding?code=${code}`)
        const data = await res.json()
        console.log('钉钉登录回调响应:', data)

        if (data && data.status === 'success' && data.data) {
          const { token, refreshToken, user } = data.data

          // 保存token和用户信息
          if (token) {
            localStorage.setItem('token', token)
          }
          if (refreshToken) {
            localStorage.setItem('refresh_token', refreshToken)
          }
          if (user) {
            localStorage.setItem('user_info', JSON.stringify(user))
          }

          // 更新 Pinia 状态
          const { useUserStore } = await import('@/stores/user')
          const userStore = useUserStore()
          userStore.login(token || refreshToken, user)

          // 根据角色跳转
          this.handlePostLoginRedirect(user)
        } else {
          throw new Error(data?.message || '钉钉登录失败')
        }
      } catch (error) {
        console.error('钉钉登录回调失败:', error)
        alert('钉钉登录失败：' + (error?.message || '未知错误'))
      }
    },

    /**
     * 账号密码登录
     */
    async handleAccountLogin() {
      if (!this.canSubmit) return
      
      this.loginLoading = true
      
      try {
        // 调用后端 GET /user/login?phone=&password_hash=
        const qs = new URLSearchParams({
          phone: this.loginForm.phone,
          // 后端期望字段名为 password_hash，这里按后端存储直接传输入值
          password_hash: this.loginForm.password
        }).toString()

        const resp = await fetch(`http://127.0.0.1:8000/user/login?${qs}`)
        const data = await resp.json()

        if (data && data.status === 'ok' && data.data && data.data.access_token) {
          const token = data.data.access_token
          const user = data.data.user

          // 本地存储
          localStorage.setItem('token', token)
          localStorage.setItem('user_info', JSON.stringify(user))

          // 更新 Pinia 状态
          const { useUserStore } = await import('@/stores/user')
          const userStore = useUserStore()
          userStore.login(token, user)

          // 根据角色跳转
          this.handlePostLoginRedirect(user)
        } else {
          throw new Error(data?.message || '登录失败')
        }
        
      } catch (error) {
        console.error('登录失败:', error)
        alert('登录失败：' + (error?.message || '未知错误'))
      } finally {
        this.loginLoading = false
      }
    },

    /**
     * 登录后根据角色跳转
     */
    handlePostLoginRedirect(user) {
      if (!user || !user.role) {
        console.error('用户信息缺失，跳转到首页')
        this.$router.replace('/')
        return
      }
      
      const role = parseInt(user.role)
      console.log('用户角色:', role, '昵称:', user.nickname)
      
      // 根据角色跳转
      if (role === 3) {
        console.log('管理员登录，跳转到管理后台')
        this.$router.replace('/admin')
      } else if (role === 2) {
        console.log('作者登录，跳转到作者中心')
        this.$router.replace('/author')
      } else {
        console.log('普通用户登录，跳转到首页')
        this.$router.replace('/')
      }
    },

    /**
     * 跳转到注册页面
     */
    goToRegister() {
      alert('注册功能待实现')
      // this.$router.push('/register')
    }
  }
}
</script>

<style scoped>
/* 全局容器动画 */
.unified-login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #e8f4f8 0%, #ffffff 50%, #fef5e7 100%);
  padding: 20px;
  animation: fadeIn 0.6s ease-out;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.login-card {
  background: white;
  border-radius: 24px;
  padding: 50px 40px;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.08), 
              0 0 0 1px rgba(255, 255, 255, 0.9) inset;
  width: 100%;
  max-width: 580px;
  animation: cardSlideIn 0.5s ease-out;
}

@keyframes cardSlideIn {
  from {
    opacity: 0;
    transform: scale(0.95) translateY(30px);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

.login-header {
  text-align: center;
  margin-bottom: 40px;
}

.main-title {
  font-size: 36px;
  color: #2c3e50;
  margin-bottom: 12px;
  font-weight: 700;
  letter-spacing: 2px;
  background: linear-gradient(135deg, #5b9bd5 0%, #ff7a41 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  animation: titleGlow 2s ease-in-out infinite;
}

@keyframes titleGlow {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.8; }
}

.subtitle {
  color: #7f8c8d;
  font-size: 15px;
  font-weight: 300;
  letter-spacing: 1px;
}

/* 登录方式切换 */
.login-tabs {
  display: flex;
  border-bottom: 2px solid #f0f4f8;
  margin-bottom: 35px;
  position: relative;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 15px 0;
  cursor: pointer;
  color: #95a5a6;
  font-size: 16px;
  position: relative;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  font-weight: 500;
}

.tab-item:hover {
  color: #3498db;
  transform: translateY(-2px);
}

.tab-item.active {
  color: #3498db;
  font-weight: 600;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 0;
  right: 0;
  height: 3px;
  background: linear-gradient(90deg, #3498db 0%, #ff7a41 100%);
  border-radius: 2px 2px 0 0;
  animation: slideIn 0.3s ease-out;
}

@keyframes slideIn {
  from {
    width: 0;
    left: 50%;
  }
  to {
    width: 100%;
    left: 0;
  }
}

/* 内容淡入动画 */
.content-fade {
  animation: contentFadeIn 0.4s ease-out;
}

@keyframes contentFadeIn {
  from {
    opacity: 0;
    transform: translateX(10px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

/* 扫码登录布局 */
.qrcode-login {
  text-align: center;
}

.login-methods {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 30px;
  align-items: stretch;
  margin-bottom: 30px;
}

/* 响应式：移动端改为上下布局 */
@media (max-width: 768px) {
  .login-methods {
    grid-template-columns: 1fr;
    gap: 20px;
  }
  
  .login-card {
    padding: 30px 25px;
  }
  
  .main-title {
    font-size: 28px;
  }
}

/* 二维码区域 */
.qrcode-section {
  background: linear-gradient(135deg, #f8fafb 0%, #ffffff 100%);
  border-radius: 16px;
  padding: 25px;
  border: 2px solid #e8f4f8;
  transition: all 0.3s ease;
}

.qrcode-section:hover {
  border-color: #3498db;
  box-shadow: 0 8px 24px rgba(52, 152, 219, 0.15);
  transform: translateY(-2px);
}

.qrcode-container {
  width: 100%;
  height: 260px;
  margin: 0 auto;
  background: #ffffff;
  border-radius: 12px;
  padding: 20px;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #e8f4f8;
  box-shadow: inset 0 2px 8px rgba(0, 0, 0, 0.03);
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: rgba(255, 255, 255, 0.98);
  border-radius: 12px;
  z-index: 10;
}

.loading-overlay p {
  color: #7f8c8d;
  font-size: 14px;
  margin-top: 15px;
}

.spinner {
  border: 4px solid #f3f4f6;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  width: 48px;
  height: 48px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 脉冲加载动画 */
.loading-placeholder {
  width: 200px;
  height: 200px;
  background: linear-gradient(135deg, #f3f4f6 0%, #e5e7eb 100%);
  border-radius: 12px;
  position: relative;
  overflow: hidden;
}

.pulse-animation {
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, 
    transparent 0%, 
    rgba(255, 255, 255, 0.8) 50%, 
    transparent 100%
  );
  animation: pulse 2s ease-in-out infinite;
}

@keyframes pulse {
  0% { transform: translateX(-100%); }
  100% { transform: translateX(100%); }
}

.qrcode-tips {
  margin-top: 20px;
}

.main-tip {
  color: #2c3e50;
  font-size: 15px;
  font-weight: 600;
  letter-spacing: 0.5px;
}

/* 快速登录按钮区域 */
.quick-login-section {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  gap: 20px;
}

.dingtalk-auth-btn-large {
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
  color: white;
  border: none;
  padding: 18px 40px;
  border-radius: 14px;
  font-size: 17px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 8px 24px rgba(52, 152, 219, 0.35);
  min-width: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  position: relative;
  overflow: hidden;
}

.dingtalk-auth-btn-large::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.3);
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s;
}

.dingtalk-auth-btn-large:hover {
  transform: translateY(-3px) scale(1.02);
  box-shadow: 0 12px 32px rgba(52, 152, 219, 0.45);
}

.dingtalk-auth-btn-large:active {
  transform: translateY(-1px) scale(0.98);
  box-shadow: 0 4px 12px rgba(52, 152, 219, 0.3);
}

.dingtalk-auth-btn-large:hover::before {
  width: 300px;
  height: 300px;
}

.btn-icon {
  font-size: 20px;
  transition: transform 0.3s;
}

.dingtalk-auth-btn-large:hover .btn-icon {
  transform: translateX(4px);
}

.quick-tip {
  margin-top: 10px;
  color: #3498db;
  font-size: 13px;
  font-weight: 500;
}

/* 功能卖点 */
.qrcode-features {
  display: flex;
  justify-content: space-around;
  padding: 25px;
  background: linear-gradient(135deg, #f8fafb 0%, #fef5e7 100%);
  border-radius: 16px;
  border: 1px solid #f0e6d2;
}

.feature-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  padding: 12px 15px;
  border-radius: 12px;
  transition: all 0.3s ease;
  flex: 1;
}

.feature-item:hover {
  background: rgba(255, 255, 255, 0.8);
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.08);
}

.feature-icon {
  font-size: 32px;
  transition: all 0.3s;
  filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
}

.feature-item:hover .feature-icon {
  transform: scale(1.2) rotate(5deg);
  filter: drop-shadow(0 4px 8px rgba(52, 152, 219, 0.3));
}

.feature-text {
  color: #34495e;
  font-size: 14px;
  font-weight: 500;
}

.feature-item:hover .feature-text {
  color: #3498db;
  font-weight: 600;
}

/* 账号密码登录 */
.account-login {
  padding: 10px 0;
}

.form-group {
  margin-bottom: 24px;
}

.form-group label {
  display: block;
  color: #2c3e50;
  font-size: 14px;
  margin-bottom: 10px;
  font-weight: 600;
  letter-spacing: 0.3px;
}

.form-input {
  width: 100%;
  padding: 14px 18px;
  border: 2px solid #e8f4f8;
  border-radius: 12px;
  font-size: 15px;
  transition: all 0.3s ease;
  box-sizing: border-box;
  background: #fafbfc;
}

.form-input:hover {
  border-color: #c8d6e0;
  background: white;
}

.form-input:focus {
  outline: none;
  border-color: #3498db;
  background: white;
  box-shadow: 0 0 0 4px rgba(52, 152, 219, 0.1);
}

.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 28px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #7f8c8d;
  transition: color 0.3s;
}

.checkbox-label:hover {
  color: #3498db;
}

.checkbox-label input[type="checkbox"] {
  cursor: pointer;
  accent-color: #3498db;
}

.forgot-link {
  color: #3498db;
  text-decoration: none;
  font-size: 14px;
  transition: all 0.3s;
  font-weight: 500;
}

.forgot-link:hover {
  color: #ff7a41;
  text-decoration: underline;
}

.login-button {
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #3498db 0%, #2980b9 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 8px 24px rgba(52, 152, 219, 0.35);
}

.login-button:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(52, 152, 219, 0.45);
}

.login-button:active:not(:disabled) {
  transform: translateY(0) scale(0.98);
}

.login-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
  transform: none;
}

.register-tip {
  text-align: center;
  margin-top: 24px;
  color: #95a5a6;
  font-size: 14px;
}

.register-tip a {
  color: #3498db;
  text-decoration: none;
  font-weight: 600;
  margin-left: 5px;
  transition: all 0.3s;
}

.register-tip a:hover {
  color: #ff7a41;
  text-decoration: underline;
}

/* 钉钉登录按钮样式 */
.dingtalk-login-section {
  margin-bottom: 30px;
}

.dingtalk-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  width: 100%;
  padding: 16px;
  background: linear-gradient(135deg, #0080FF 0%, #0051D5 100%);
  color: white;
  text-decoration: none;
  border-radius: 12px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 8px 24px rgba(0, 128, 255, 0.35);
  border: none;
}

.dingtalk-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 12px 32px rgba(0, 128, 255, 0.45);
}

.dingtalk-btn:active {
  transform: translateY(0) scale(0.98);
}

.dingtalk-btn .btn-icon {
  font-size: 20px;
}

/* 分隔线 */
.divider {
  display: flex;
  align-items: center;
  text-align: center;
  margin: 25px 0;
  position: relative;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  border-bottom: 2px solid #e8f4f8;
}

.divider span {
  padding: 0 15px;
  color: #95a5a6;
  font-size: 14px;
  font-weight: 500;
  background: white;
  position: relative;
}
</style>

